package com.example.ymm.config;


import com.example.ymm.bo.YmUserDetails;
import com.example.ymm.model.CommonResult;
import com.example.ymm.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring security处理器
 *
 * @author wpw
 */
@Configuration
public class SecurityHandlerConfig {

    //	@Autowired
//	private TokenService tokenService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    /**
     * 登陆成功，返回Token
     *
     * @return
     */
    @Bean
    public AuthenticationSuccessHandler loginSuccessHandler() {
        return new AuthenticationSuccessHandler() {

            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                                Authentication authentication) throws IOException, ServletException {
                YmUserDetails loginUser = (YmUserDetails) authentication.getPrincipal();
//				HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
//				requestWrapper.addHeader(tokenHeader, loginUser.getToken());
//				request = requestWrapper;

            }
        };
    }

    /**
     * 登陆失败
     *
     * @return
     */
    @Bean
    public AuthenticationFailureHandler loginFailureHandler() {
        return new AuthenticationFailureHandler() {

            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                                AuthenticationException exception) throws IOException, ServletException {
                String msg = null;
                if (exception instanceof BadCredentialsException) {
                    msg = "密码错误";
                } else {
                    msg = exception.getMessage();
                }

                ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), CommonResult.validateFailed(msg));
            }
        };

    }

    /**
     * 未登录，返回401
     *
     * @return
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new AuthenticationEntryPoint() {

            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response,
                                 AuthenticationException authException) throws IOException, ServletException {
                ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), CommonResult.validateFailed("请先登录"));
            }
        };
    }

    /**
     * 退出处理 401
     *
     * @return
     */
    @Bean
    public LogoutSuccessHandler logoutSussHandler() {
        return new LogoutSuccessHandler() {

            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
                ResponseUtil.responseJson(response, HttpStatus.OK.value(), CommonResult.logout("退出登录成功!"));
            }
        };

    }


}
